package talex.zsw.smartsport.util.common

import android.content.Context
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup

/**
 * 作用: 简易通用的Behavior方法
 * 作者: 赵小白 email:edisonzsw@icloud.com 
 * 日期: 2016/12/23 09:00 
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class CommonBehavior(private val mContext: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<View>()
{
    private var sinceDirectionChange: Int = 0

    //判断滑动的方向 我们需要垂直滑动
    override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: View, directTargetChild: View, target: View, axes: Int, type: Int): Boolean
    {
        return axes and ViewCompat.SCROLL_AXIS_VERTICAL != 0
    }

    override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: View, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int)
    {
        if (dy > 0 && sinceDirectionChange < 0 || dy < 0 && sinceDirectionChange > 0)
        {
            child!!.animate().cancel()
            sinceDirectionChange = 0
        }
        sinceDirectionChange += dy
        if (sinceDirectionChange > child!!.height && child.visibility == View.VISIBLE)
        {
            // 向上滑
        }
        else if (sinceDirectionChange < 0 && child.visibility == View.GONE)
        {
            // 向下滑
        }
    }

    override fun layoutDependsOn(parent: CoordinatorLayout, child: View, dependency: View): Boolean
    {
        // 设置从属View继承 dependency 的继承
        return dependency is AppBarLayout
    }

    /**
     * @param parent CoordinatorLayout
     * *
     * @param child 目标View,设置layout_behavior的View
     * *
     * @param dependency 从属View,大部分情况是AppBarLayout
     */
    override fun onDependentViewChanged(parent: CoordinatorLayout, child: View, dependency: View): Boolean
    {
        return true
    }

    /**
     * 设置View的位置
     */
    private fun setPosition(v: View, x: Int, y: Int)
    {
        val layoutParams = v.layoutParams as ViewGroup.MarginLayoutParams
        layoutParams.leftMargin = x
        layoutParams.topMargin = y
        v.layoutParams = layoutParams
    }
}